#!/usr/bin/env python
#
# expand is used to reconstruct the entire wiki from a single file.
#
# This is a submodule of warbler (warbler.org)
#
# Copyright (c) 2008 by Patrick Maupin <pmaupin@gmail.com>

import os
import glob
from wiki_report import WikiInfo
from wiki_parse import splitstring, RefString

navinfo = dict(((x,x) for x in WikiInfo.pageorder))

toolsdir = os.path.dirname(__file__)
srcname = os.path.join(toolsdir, 'entire_wiki.txt')
dstnames = os.path.join(os.path.abspath(os.path.join(toolsdir, '..')), '%s.wiki')

f = open(srcname, 'rb')
data = f.read()
f.close()

print WikiInfo.singular
for name in WikiInfo.singular:
    data = data.split(name)
    while len(data) > 1:
        index = len(data) - 2
        prevstr, nextstr = data[index], data[-1]
        nochange = prevstr[-1].isalpha() or nextstr[0].isalpha()
        nochange = nochange or prevstr.rfind('[') > prevstr.rfind(']')
        if nochange:
            if prevstr[-1] == '[' and nextstr[0] != 's':
                print "Warning", repr((prevstr[-10:], name, nextstr[:30]))
                #data[index] += '%ss%s' % (name, data.pop())
            #else:
            data[index] += '%s%s' % (name, data.pop())
        else:
            data[index] += '[%ss %s]%s' % (name, name, data.pop())
    data = data[0]

data = data.replace('\n..', '\n ..').split('\n.')
assert not data[0].replace('-', '').strip(), repr(data[0])
del data[0]

data = [x.split('\n\n', 1) for x in data]
for stuff in data:
    assert len(stuff) == 2 and stuff[0].isalpha(), repr(stuff[0])

def add_navigation(fname, fdata):
    nav = navinfo.get(fname, None)
    fdata = fdata.strip().splitlines()
    while not fdata[-1].replace('-', '').strip():
        fdata.pop()
    if not nav:
        fdata.append('')
        return '\n'.join(fdata)
    index = 0
    while index < len(fdata):
        test = fdata[index].strip()
        if test and not test.startswith('#'):
            break
        index += 1

    hierarchy = [nav]
    while hierarchy[-1].parent != hierarchy[-1]:
        hierarchy.append(hierarchy[-1].parent)
    hierarchy.append('[http://code.google.com/p/warbler/ warbler]')
    hierarchy.reverse()
    hierarchy = '* %s *' % ' / '.join(hierarchy)
    nav = nav.prevchapter, nav.prev, nav.next, nav.nextchapter
    nav = ['|| *[%s %s]* ' % x for x in zip(nav, '<<==== <===  ===> ====>>'.split())]
    nav.append('||')
    nav = ''.join(nav)
    fdata[index:index] = ['%s %s ||' % (nav, hierarchy), '']
    fdata.extend(['', nav, ''])
    return '\n'.join(fdata)

def writefile(fname, fdata):
    f = open(dstnames % fname, 'wb')
    f.write(fdata)
    f.close()

for fname, fdata in data:
    if fname != 'CatchAll':
        writefile(fname, add_navigation(fname, fdata))

def writesinglepage(fname, datadict):
    result = ['#summary Automatically generated single page version of the warbler manual']
    pageorder = WikiInfo.pageorder
    targets = {}
    for page in pageorder:
        info = ('\n' + datadict.get(page, '')).split('\n#summary ', 1)
        summary = page
        if len(info) > 1:
            summary, info[1] = info[1].split('\n', 1)
        else:
            print page, "has no summary information"
        info = '\n'.join(info)
        header = page.indent * '='
        result.append('%s %s %s' % (header, summary, header))
        result.append(info.strip())
        targets[page] = summary.replace(' ', '_')
    for page in WikiInfo.singular:
        targets[page] = targets[page+'s']
    result.append('')
    result = '\n\n'.join(result)
    result = list(splitstring(result))
    for index, s in enumerate(result):
        if isinstance(s, RefString) and s.target in targets:
            result[index] = '[#%s %s]' % (targets[s.target], s.name)
    writefile(fname, ''.join(result))

writesinglepage('SinglePageWarblerManual', dict(data))
